﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dto = BloxDTO;
using BloxServer2012.Database;

namespace BloxServer2012
{
    public class DataAccess
    {
        public static databaseEntities Database;
        public static void Connect()
        {
            Database = new databaseEntities();
        }

        public static int CreateWorld(string name)
        {
            if (Database.Worlds.Any(world => world.Name == name))
                return 1;
            Database.Worlds.Add(new World() { Name = name });
            Database.SaveChanges();
            return 0;
        }

        public static int CreatePlayer(string name)
        {
            if (Database.Players.Any(player => player.Name == name))
                return 1;
            Database.Players.Add(new Player() { Name = name });
            Database.SaveChanges();
            return 0;
        }

        public static int CreateRegion(int X, int Y, int Z, dto.RegionType type, long worldID, string name = null)
        {
            if (Database.Regions.Any(region => region.X == X && region.Y == Y && region.Z == Z && region.WorldID == worldID))
                return 1;
            Database.Regions.Add(new Region() { X = X, Y = Y, Z = Z, Type = (int)type, WorldID = worldID, Name = name });
            Database.SaveChanges();
            return 0;
        }

        public static int CreateChunk(int X, int Y, int Z, long regionID, int Size = 16)
        {
            if (Database.Chunks.Any(chunk => chunk.X == X && chunk.Y == Y && chunk.Z == Z && chunk.RegionID == regionID))
                return 1;
            WorldGen.Chunk c = new WorldGen.Chunk(Size);
            Chunk newChunk = new Chunk() { X = X, Y = Y, Z = Z, RegionID = regionID };
            for (int x = 0; x < Size; x++)
            {
                for (int y = 0; y < Size; y++)
                {
                    for (int z = 0; z < Size; z++)
                    {
                        if (c.blocksSolid[x, y, z] != dto.BlockType.Air)
                            newChunk.Blocks.Add(new Block() { Chunk = newChunk, TypeID = (long)c.blocksSolid[x, y, z], X = x, Y = y, Z = z });
                    }
                }
            }
            Database.Chunks.Add(newChunk);
            Database.SaveChanges();
            return 0;
        }
    }
}
